package co.edu.unal.satacredito.administration.service.user;

import javax.faces.context.FacesContext;

import co.edu.unal.satacredito.administration.util.SatacreditoConstants;
import co.edu.unal.satacredito.administration.util.SessionUtil;
import co.edu.unal.satacredito.infrastructure.dto.UserDTO;

public class UserViewService {
	
	/**
	 * Log the user in
	 * @param username
	 * @param password
	 * @return
	 */
	public void saveUserInSession(UserDTO userDTO) {		
		// yo por ahora guardo un DTO en sesion
		SessionUtil.storeInSession(FacesContext.getCurrentInstance()
				.getExternalContext(), SatacreditoConstants.SESSION_USER_KEY,
				userDTO);
	}
	
	/**
	 * Log the user out
	 */
	public void doLogout() {
		SessionUtil.closeSession(FacesContext.getCurrentInstance()
				.getExternalContext());
	}

	/**
	 * Checks if the user is logged in
	 * 
	 * @return
	 */
	public boolean isLoggedIn() {
		try {
			UserDTO userSession = (UserDTO) SessionUtil.retrieveFromSession(
					FacesContext.getCurrentInstance().getExternalContext(),
					SatacreditoConstants.SESSION_USER_KEY);

			if (userSession != null && userSession.getName().length() > 0) {
				return true;
			}

			return false;
		} catch (Exception e) {
			return false;
		}
	}

}
